#include <iostream>
#include <vector>

using namespace std;
// 144.二叉树的前序遍历
// 给你二叉树的根节点 root ，返回它节点值的 前序 遍历。
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode():val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x):val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right): val(x), left(left), right(right) {}
};
class Solution {
private:
    void preOrder(TreeNode* root, vector<int>& res){
        if(root != nullptr) {
            res.push_back(root->val);
            preOrder(root->left,res);
            preOrder(root->right,res);
        }
    }
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> res;
        preOrder(root, res);
        return res;
    }
};
void printRes(vector<int>& res) {
    cout << "[";
    for(int i = 0; i < res.size(); i++) {
        cout << res[i] << (i < res.size()-1 ? "," : "");
    }
    cout << "]" << endl;
}
int main() {
    // root = [1,null,2,3]
    TreeNode* root1 = new TreeNode(1, nullptr, new TreeNode(2, new TreeNode(3), nullptr));
    vector<int> res = Solution().preorderTraversal(root1);  // [1,2,3]
    printRes(res);
    // root = []
    TreeNode* root2 = nullptr;
    res = Solution().preorderTraversal(root2);  // []
    printRes(res);
    // root = [1]
    TreeNode* root3 = new TreeNode(1);
    res = Solution().preorderTraversal(root3);  // [1]
    printRes(res);
    // root = [1,2]
    TreeNode* root4 = new TreeNode(1,new TreeNode(2), nullptr);
    res = Solution().preorderTraversal(root4);  // [1,2]
    printRes(res);
    // root = [1,null,2]
    TreeNode* root5 = new TreeNode(1, nullptr,new TreeNode(2));
    res = Solution().preorderTraversal(root5);  // [1,2]
    printRes(res);
    return 0;
}
